import { useState } from 'react'
import { AutoComplete } from 'antd'
import { useGetState } from '@/hooks/useRedux'
import { GlobalInitialState } from '@/redux/slices/global.slice'
import { debounce } from 'lodash'
import { useNavigate } from 'react-router-dom'

type OptionsType = {
    value: string
    path: string
}

export default function Search() {
    const { authMenuList } = useGetState<GlobalInitialState>('global')
    const navigate = useNavigate()
    const [options, setOptions] = useState<OptionsType[]>([])

    // 搜索
    const onSearch = debounce((searchText: string) => {
        const menuFilterList = authMenuList.filter((item) => {
            return searchText.trim().length > 0 && item?.label?.toString()?.indexOf(searchText.trim()) !== -1
        })
        setOptions(
            menuFilterList.map((item) => {
                return {
                    value: item?.label?.toString()!,
                    path: item.key!,
                }
            })
        )
    }, 200)

    // 选择的菜单
    const onSelect = (data: string) => {
        const option = options.filter((item) => item.value === data)[0]
        navigate(option.path)
    }

    return (
        authMenuList.length > 2 && (
            <AutoComplete
                className="search-menu"
                allowClear
                options={options}
                style={{ width: 200 }}
                onSelect={onSelect}
                onSearch={onSearch}
                placeholder="搜索菜单"
            />
        )
    )
}
